import io from 'socket.io-client';

// 创建Socket连接
// 使用正确的相对路径连接
const socket = io('/');

// 封装socket服务
const socketService = {
  // 请求初始数据
  requestInitialData(callback) {
    socket.emit('request-initial-data');
    socket.once('initial_data', (data) => {
      callback(data);
    });
  },

  // 订阅设备更新
  subscribeToDeviceUpdates(deviceType, callback) {
    let eventName;
    switch (deviceType) {
      case 'temperature':
        eventName = 'temperature_update';
        break;
      case 'led':
        eventName = 'led_state_update';
        break;
      case 'servo':
        eventName = 'servo_state_update';
        break;
      case 'barometric-pressure':
        eventName = 'barometric_pressure_update';
        break;
      default:
        eventName = `${deviceType}_update`;
    }

    const handler = (data) => {
      callback(data);
    };

    socket.on(eventName, handler);

    // 返回取消订阅函数
    return () => {
      socket.off(eventName, handler);
    };
  },

  // 控制LED
  controlLed(state) {
    this.sendControlCommand('led', state);
  },
  // 控制舵机
  controlServo(state) {
    this.sendControlCommand('servo', state);
  },

  // 发送控制命令
  sendControlCommand(deviceType, command) {
    let eventName;
    switch(deviceType) {
      case 'led':
        eventName = 'control_led';
        break;
      case 'servo':
        eventName = 'control_servo';
        break;
      default:
        eventName = `control_${deviceType}`;
    }

    socket.emit(eventName, command);
  }
};

export default socketService;